import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Progress,
  Tag,
  Typography,
  Space,
  Button,
  Select,
  DatePicker,
  Alert,
  List,
  Avatar,
  Tooltip,
  Badge,
  Divider,
  Tabs,
  message,
  Empty,
  Spin,
  Modal,
  Form,
  Input,
  Collapse,
  Timeline,
  Descriptions,
} from "antd";
import {
  UserOutlined,
  TeamOutlined,
  BookOutlined,
  TrophyOutlined,
  RiseOutlined,
  FallOutlined,
  ClockCircleOutlined,
  FireOutlined,
  EyeOutlined,
  DownloadOutlined,
  PrinterOutlined,
  ReloadOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  StarOutlined,
  GlobalOutlined,
  DashboardOutlined,
  BellOutlined,
  RobotOutlined,
  SyncOutlined,
  LoadingOutlined,
  FileTextOutlined,
  BarChartOutlined,
  SecurityScanOutlined,
  BulbOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  ExclamationCircleFilled,
  InfoCircleFilled,
} from "@ant-design/icons";
import {
  BarChart,
  Bar as RechartsBar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  LineChart,
  Line as RechartsLine,
  PieChart,
  Pie as RechartsPie,
  Cell,
  ResponsiveContainer,
  AreaChart,
  Area as RechartsArea,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from "recharts";
import styled from "styled-components";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { adminAPI } from "../../../services/api";
import { useUser } from "../../../contexts/UserContext";
import PDFReportGenerator from "../../../components/PDFReportGenerator";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title as ChartTitle,
  Tooltip as ChartTooltip,
  Legend as ChartLegend,
  ArcElement,
  PointElement,
  LineElement,
  Filler,
} from 'chart.js';
import { Bar, Pie, Line, Doughnut } from 'react-chartjs-2';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  ChartTitle,
  ChartTooltip,
  ChartLegend,
  ArcElement,
  PointElement,
  LineElement,
  Filler
);

dayjs.extend(relativeTime);

const { Title, Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

// 类型定义
interface SystemOverview {
  totalUsers: number;
  totalStudents: number;
  totalTeachers: number;
  totalCourses: number;
  totalExams: number;
  activeUsers: number;
  systemHealth: number;
  serverStatus: "healthy" | "warning" | "error";
}

interface UserStatistics {
  userGrowth: Array<{ date: string; students: number; teachers: number }>;
  userDistribution: Array<{ name: string; value: number; color: string }>;
  activeUserTrend: Array<{
    date: string;
    activeUsers: number;
    loginRate: number;
  }>;
  topActiveUsers: Array<{
    id: string;
    name: string;
    role: string;
    avatar?: string;
    activityScore: number;
    lastActive: string;
  }>;
}

interface CourseAnalytics {
  popularCourses: Array<{
    id: string;
    name: string;
    enrollments: number;
    completion: number;
    rating: number;
    category: string;
  }>;
  categoryDistribution: Array<{
    category: string;
    count: number;
    percentage: number;
  }>;
  performanceMetrics: Array<{
    subject: string;
    average: number;
    passRate: number;
  }>;
}

interface SystemAlert {
  id: string;
  type: "info" | "warning" | "error" | "success";
  title: string;
  description: string;
  timestamp: Date;
  resolved: boolean;
}

interface AIAnalysisResult {
  id: string;
  timestamp: Date;
  analysisType: "user_behavior" | "system_performance" | "security_risk" | "data_trends";
  summary: string;
  keyFindings: string[];
  recommendations: string[];
  confidence: number;
  status: "pending" | "processing" | "completed" | "failed";
}

// AI报告相关接口
interface AIReportSection {
  title: string;
  icon: React.ReactNode;
  content: string;
  keyPoints: string[];
  status: "positive" | "negative" | "neutral" | "warning";
}

interface AIReport {
  id: string;
  title: string;
  generatedAt: Date;
  timeRange: string;
  summary: string;
  sections: AIReportSection[];
  overallScore: number;
  status: "generating" | "completed" | "failed";
  recommendations: string[];
  nextSteps: string[];
}

const DashboardContainer = styled.div`
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
`;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  .ant-card-head {
    border-bottom: 1px solid #f0f0f0;
    background: linear-gradient(135deg, #fafafa 0%, #fff 100%);
    border-radius: 12px 12px 0 0;
  }

  .ant-card-head-title {
    font-weight: 600;
    font-size: 16px;
    color: #262626;
  }
`;

const MetricCard = styled(Card)`
  text-align: center;
  border-radius: 12px;
  background: linear-gradient(135deg, #fff 0%, #fafafa 100%);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }

  .metric-content {
    padding: 20px;
  }

  .metric-icon {
    font-size: 32px;
    margin-bottom: 12px;
    background: linear-gradient(135deg, #1890ff, #40a9ff);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .metric-value {
    font-size: 28px;
    font-weight: bold;
    color: #262626;
    margin-bottom: 8px;
  }

  .metric-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
  }

  .metric-trend {
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
  }
`;

const QuickActionButton = styled(Button)`
  height: 48px;
  border-radius: 8px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  }
`;

const AlertCard = styled.div<{ type: string }>`
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 12px;
  border-left: 4px solid
    ${(props) =>
      props.type === "error"
        ? "#ff4d4f"
        : props.type === "warning"
          ? "#faad14"
          : props.type === "success"
            ? "#52c41a"
            : "#1890ff"};
  background: ${(props) =>
    props.type === "error"
      ? "#fff1f0"
      : props.type === "warning"
        ? "#fffbe6"
        : props.type === "success"
          ? "#f6ffed"
          : "#e6f7ff"};

  .alert-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .alert-title {
    font-weight: 600;
    font-size: 14px;
    color: #262626;
  }

  .alert-time {
    font-size: 12px;
    color: #999;
  }

  .alert-description {
    font-size: 13px;
    color: #666;
    line-height: 1.5;
  }
`;

const COLORS = [
  "#1890ff",
  "#52c41a",
  "#faad14",
  "#f5222d",
  "#722ed1",
  "#13c2c2",
  "#eb2f96",
  "#fa8c16",
];

const AdminDashboard: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState("overview");
  const [timeRange, setTimeRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, "days"),
    dayjs(),
  ]);

  // 数据状态
  const [systemOverview, setSystemOverview] = useState<SystemOverview | null>(
    null
  );
  const [userStatistics, setUserStatistics] = useState<UserStatistics | null>(
    null
  );
  const [courseAnalytics, setCourseAnalytics] =
    useState<CourseAnalytics | null>(null);
  const [systemAlerts, setSystemAlerts] = useState<SystemAlert[]>([]);
  const [aiAnalysisResults, setAiAnalysisResults] = useState<AIAnalysisResult[]>([]);
  const [aiAnalyzing, setAiAnalyzing] = useState(false);

  // AI报告相关状态
  const [aiReportModalVisible, setAiReportModalVisible] = useState(false);
  const [aiReport, setAiReport] = useState<AIReport | null>(null);
  const [generatingReport, setGeneratingReport] = useState(false);
  const [reportForm] = Form.useForm();
  const [shouldGeneratePDF, setShouldGeneratePDF] = useState(false);

  // 生成模拟数据
  const generateMockData = () => {
    const mockOverview: SystemOverview = {
      totalUsers: 810,
      totalStudents: 789,
      totalTeachers: 20,
      totalCourses: 45,
      totalExams: 23,
      activeUsers: 567,
      systemHealth: 96.5,
      serverStatus: "healthy",
    };

    const mockUserStats: UserStatistics = {
      userGrowth: Array.from({ length: 30 }, (_, i) => ({
        date: dayjs()
          .subtract(29 - i, "days")
          .format("MM-DD"),
        students: Math.floor(Math.random() * 50) + 20,
        teachers: Math.floor(Math.random() * 8) + 2,
      })),
      userDistribution: [
        { name: "学生", value: 789, color: "#1890ff" },
        { name: "教师", value: 20, color: "#52c41a" },
        { name: "管理员", value: 1, color: "#faad14" },
      ],
      activeUserTrend: Array.from({ length: 7 }, (_, i) => ({
        date: dayjs()
          .subtract(6 - i, "days")
          .format("MM-DD"),
        activeUsers: Math.floor(Math.random() * 200) + 600,
        loginRate: Math.floor(Math.random() * 20) + 70,
      })),
      topActiveUsers: [
        {
          id: "1",
          name: "李明轩",
          role: "学生",
          activityScore: 98,
          lastActive: "3分钟前",
        },
        {
          id: "2",
          name: "张教授",
          role: "教师",
          activityScore: 96,
          lastActive: "8分钟前",
        },
        {
          id: "3",
          name: "王雨涵",
          role: "学生",
          activityScore: 94,
          lastActive: "12分钟前",
        },
        {
          id: "4",
          name: "陈副教授",
          role: "教师",
          activityScore: 91,
          lastActive: "18分钟前",
        },
        {
          id: "5",
          name: "张浩然",
          role: "学生",
          activityScore: 89,
          lastActive: "25分钟前",
        },
      ],
    };

    const mockCourseAnalytics: CourseAnalytics = {
      popularCourses: [
        {
          id: "1",
          name: "高等数学(一)",
          enrollments: 456,
          completion: 92,
          rating: 4.6,
          category: "数学基础",
        },
        {
          id: "2",
          name: "大学英语(一)",
          enrollments: 423,
          completion: 89,
          rating: 4.5,
          category: "语言基础",
        },
        {
          id: "3",
          name: "Python程序设计",
          enrollments: 234,
          completion: 95,
          rating: 4.8,
          category: "计算机基础",
        },
        {
          id: "4",
          name: "数据结构与算法",
          enrollments: 198,
          completion: 87,
          rating: 4.7,
          category: "计算机基础",
        },
        {
          id: "5",
          name: "大学物理(一)",
          enrollments: 187,
          completion: 91,
          rating: 4.4,
          category: "物理基础",
        },
      ],
      categoryDistribution: [
        { category: "数学基础", count: 8, percentage: 17.8 },
        { category: "计算机基础", count: 12, percentage: 26.7 },
        { category: "语言基础", count: 6, percentage: 13.3 },
        { category: "物理基础", count: 5, percentage: 11.1 },
        { category: "软件开发", count: 7, percentage: 15.6 },
        { category: "其他专业", count: 7, percentage: 15.6 },
      ],
      performanceMetrics: [
        { subject: "高等数学", average: 82.5, passRate: 94.2 },
        { subject: "大学英语", average: 85.8, passRate: 96.7 },
        { subject: "Python程序设计", average: 87.2, passRate: 98.5 },
        { subject: "数据结构", average: 84.3, passRate: 92.8 },
        { subject: "大学物理", average: 80.7, passRate: 91.5 },
      ],
    };

    const mockAlerts: SystemAlert[] = [
      {
        id: "1",
        type: "warning",
        title: "服务器负载较高",
        description: "当前服务器CPU使用率达到85%，建议关注系统性能",
        timestamp: new Date(Date.now() - 15 * 60 * 1000),
        resolved: false,
      },
      {
        id: "2",
        type: "info",
        title: "新用户注册激增",
        description: "今日新注册用户数量比昨日增长45%",
        timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
        resolved: false,
      },
      {
        id: "3",
        type: "success",
        title: "系统更新完成",
        description: "教学平台v2.1更新已成功部署，新功能已上线",
        timestamp: new Date(Date.now() - 4 * 60 * 60 * 1000),
        resolved: true,
      },
      {
        id: "4",
        type: "error",
        title: "数据库连接异常",
        description: "部分用户报告无法访问学习记录，正在紧急修复",
        timestamp: new Date(Date.now() - 6 * 60 * 60 * 1000),
        resolved: true,
      },
    ];

    // 生成AI分析结果
    const mockAIAnalysisResults: AIAnalysisResult[] = [
      {
        id: "1",
        timestamp: new Date(Date.now() - 30 * 60 * 1000),
        analysisType: "user_behavior",
        summary: "用户行为分析显示，学生群体在晚间时段活跃度较高，建议优化晚间服务性能",
        keyFindings: [
          "晚间8-10点是用户活跃高峰期",
          "移动端访问占比达到65%",
          "视频学习内容受欢迎度最高",
          "用户平均学习时长呈上升趋势"
        ],
        recommendations: [
          "增加晚间服务器资源",
          "优化移动端用户体验",
          "增加视频教学内容",
          "实施个性化学习推荐"
        ],
        confidence: 94.5,
        status: "completed"
      },
      {
        id: "2",
        timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
        analysisType: "system_performance",
        summary: "系统性能分析发现数据库查询效率有待提升，建议优化索引结构",
        keyFindings: [
          "数据库响应时间平均为120ms",
          "慢查询主要集中在用户信息表",
          "缓存命中率偏低，仅65%",
          "系统整体稳定性良好"
        ],
        recommendations: [
          "优化数据库索引",
          "增加缓存策略",
          "实施读写分离",
          "定期清理无用数据"
        ],
        confidence: 89.2,
        status: "completed"
      },
      {
        id: "3",
        timestamp: new Date(Date.now() - 4 * 60 * 60 * 1000),
        analysisType: "security_risk",
        summary: "安全风险评估显示系统整体安全状况良好，但需关注异常登录行为",
        keyFindings: [
          "检测到3个可疑IP地址",
          "用户密码强度普遍较高",
          "未发现严重安全漏洞",
          "API访问频率正常"
        ],
        recommendations: [
          "加强异常登录监控",
          "实施IP白名单机制",
          "定期安全扫描",
          "用户安全意识培训"
        ],
        confidence: 92.8,
        status: "completed"
      }
    ];

    setSystemOverview(mockOverview);
    setUserStatistics(mockUserStats);
    setCourseAnalytics(mockCourseAnalytics);
    setSystemAlerts(mockAlerts);
    setAiAnalysisResults(mockAIAnalysisResults);
  };

  // 数据加载
  const loadData = async () => {
    setLoading(true);
    try {
      // 直接使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 500)); // 模拟加载延迟
      generateMockData();
    } catch (error) {
      message.error("数据加载失败，请稍后重试");
      console.error("加载管理员仪表板数据失败:", error);
      // 即使出错也生成默认数据
      generateMockData();
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [timeRange]);

  // 渲染系统概览指标
  const renderSystemMetrics = () => {
    if (!systemOverview) return null;

    const metrics = [
      {
        title: "用户总数",
        value: systemOverview.totalUsers,
        icon: <TeamOutlined />,
        trend: { value: 12.5, isUp: true },
        color: "#1890ff",
      },
      {
        title: "活跃用户",
        value: systemOverview.activeUsers,
        icon: <UserOutlined />,
        trend: { value: 8.3, isUp: true },
        color: "#52c41a",
      },
      {
        title: "课程总数",
        value: systemOverview.totalCourses,
        icon: <BookOutlined />,
        trend: { value: 5.7, isUp: true },
        color: "#faad14",
      },
      {
        title: "考试总数",
        value: systemOverview.totalExams,
        icon: <TrophyOutlined />,
        trend: { value: 15.2, isUp: true },
        color: "#722ed1",
      },
    ];

    return (
      <Row gutter={[24, 24]}>
        {metrics.map((metric, index) => (
          <Col span={6} key={index}>
            <MetricCard>
              <div className="metric-content">
                <div className="metric-icon" style={{ color: metric.color }}>
                  {metric.icon}
                </div>
                <div className="metric-value">
                  {metric.value.toLocaleString()}
                </div>
                <div className="metric-label">{metric.title}</div>
                <div className="metric-trend">
                  {metric.trend.isUp ? (
                    <RiseOutlined style={{ color: "#52c41a" }} />
                  ) : (
                    <FallOutlined style={{ color: "#ff4d4f" }} />
                  )}
                  <span
                    style={{ color: metric.trend.isUp ? "#52c41a" : "#ff4d4f" }}
                  >
                    {metric.trend.value}%
                  </span>
                  <span style={{ color: "#999" }}>vs 上月</span>
                </div>
              </div>
            </MetricCard>
          </Col>
        ))}
      </Row>
    );
  };

  // 渲染用户增长图表
  const renderUserGrowthChart = () => {
    if (!userStatistics) return null;

    return (
      <ResponsiveContainer width="100%" height={300}>
        <AreaChart data={userStatistics.userGrowth}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="date" />
          <YAxis />
          <RechartsTooltip />
          <Legend />
          <RechartsBar
            type="monotone"
            dataKey="students"
            stackId="1"
            stroke="#1890ff"
            fill="#1890ff"
            name="学生注册"
          />
          <RechartsBar
            type="monotone"
            dataKey="teachers"
            stackId="1"
            stroke="#52c41a"
            fill="#52c41a"
            name="教师注册"
          />
        </AreaChart>
      </ResponsiveContainer>
    );
  };

  // 渲染用户分布饼图
  const renderUserDistributionChart = () => {
    if (!userStatistics) return null;

    return (
      <ResponsiveContainer width="100%" height={300}>
        <PieChart>
          <RechartsPie
            data={userStatistics.userDistribution}
            cx="50%"
            cy="50%"
            outerRadius={80}
            fill="#8884d8"
            dataKey="value"
            label={({ name, percent }) =>
              `${name} ${(percent * 100).toFixed(0)}%`
            }
          >
            {userStatistics.userDistribution.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={entry.color} />
            ))}
          </RechartsPie>
          <RechartsTooltip />
        </PieChart>
      </ResponsiveContainer>
    );
  };

  // 渲染课程分析雷达图
  const renderPerformanceRadarChart = () => {
    if (!courseAnalytics) return null;

    return (
      <ResponsiveContainer width="100%" height={400}>
        <RadarChart data={courseAnalytics.performanceMetrics}>
          <PolarGrid />
          <PolarAngleAxis dataKey="subject" />
          <PolarRadiusAxis angle={90} domain={[0, 100]} />
          <Radar
            name="平均分"
            dataKey="average"
            stroke="#1890ff"
            fill="#1890ff"
            fillOpacity={0.3}
          />
          <Radar
            name="通过率"
            dataKey="passRate"
            stroke="#52c41a"
            fill="#52c41a"
            fillOpacity={0.3}
          />
          <Legend />
        </RadarChart>
      </ResponsiveContainer>
    );
  };

  // 渲染热门课程表格
  const renderPopularCoursesTable = () => {
    if (!courseAnalytics) return null;

    const columns = [
      {
        title: "课程名称",
        dataIndex: "name",
        key: "name",
        render: (name: string, record: any) => (
          <Space>
            <Avatar
              icon={<BookOutlined />}
              style={{ backgroundColor: "#1890ff" }}
            />
            <div>
              <div style={{ fontWeight: 500 }}>{name}</div>
              <Tag color="blue">{record.category}</Tag>
            </div>
          </Space>
        ),
      },
      {
        title: "报名人数",
        dataIndex: "enrollments",
        key: "enrollments",
        sorter: (a: any, b: any) => a.enrollments - b.enrollments,
        render: (value: number) => (
          <Space>
            <TeamOutlined style={{ color: "#1890ff" }} />
            <span style={{ fontWeight: 500 }}>{value}</span>
          </Space>
        ),
      },
      {
        title: "完成率",
        dataIndex: "completion",
        key: "completion",
        render: (completion: number) => (
          <Progress
            percent={completion}
            size="small"
            strokeColor="#52c41a"
            format={(percent) => `${percent}%`}
          />
        ),
      },
      {
        title: "评分",
        dataIndex: "rating",
        key: "rating",
        render: (rating: number) => (
          <Space>
            <StarOutlined style={{ color: "#faad14" }} />
            <span style={{ fontWeight: 500 }}>{rating}</span>
          </Space>
        ),
      },
      {
        title: "操作",
        key: "action",
        render: () => (
          <Space>
            <Button type="link" size="small" icon={<EyeOutlined />}>
              查看详情
            </Button>
          </Space>
        ),
      },
    ];

    return (
      <Table
        columns={columns}
        dataSource={courseAnalytics.popularCourses}
        rowKey="id"
        pagination={{ pageSize: 5, showSizeChanger: false }}
        size="small"
      />
    );
  };

  // 渲染系统警告
  const renderSystemAlerts = () => {
    const unResolvedAlerts = systemAlerts.filter((alert) => !alert.resolved);

    if (unResolvedAlerts.length === 0) {
      return (
        <Empty
          description="暂无系统警告"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          style={{ padding: "40px 0" }}
        />
      );
    }

    return (
      <div>
        {unResolvedAlerts.map((alert) => (
          <AlertCard key={alert.id} type={alert.type}>
            <div className="alert-header">
              <span className="alert-title">{alert.title}</span>
              <span className="alert-time">
                {dayjs(alert.timestamp).fromNow()}
              </span>
            </div>
            <div className="alert-description">{alert.description}</div>
          </AlertCard>
        ))}
      </div>
    );
  };

  // 渲染活跃用户排行
  const renderActiveUsersRanking = () => {
    if (!userStatistics) return null;

    return (
      <List
        dataSource={userStatistics.topActiveUsers}
        renderItem={(user, index) => (
          <List.Item>
            <List.Item.Meta
              avatar={
                <Badge count={index + 1} style={{ backgroundColor: "#1890ff" }}>
                  <Avatar
                    icon={<UserOutlined />}
                    style={{
                      backgroundColor:
                        user.role === "教师" ? "#52c41a" : "#faad14",
                    }}
                  />
                </Badge>
              }
              title={
                <Space>
                  <span style={{ fontWeight: 500 }}>{user.name}</span>
                  <Tag color={user.role === "教师" ? "green" : "blue"}>
                    {user.role}
                  </Tag>
                </Space>
              }
              description={
                <Space>
                  <span>活跃度: {user.activityScore}分</span>
                  <Divider type="vertical" />
                  <span>最后活跃: {user.lastActive}</span>
                </Space>
              }
            />
            <Progress
              percent={user.activityScore}
              size="small"
              strokeColor="#1890ff"
              showInfo={false}
              style={{ width: 100 }}
            />
          </List.Item>
        )}
      />
    );
  };

  // 生成新的AI分析结果
  const generateNewAIAnalysis = async () => {
    setAiAnalyzing(true);
    try {
      // 模拟AI分析生成
      await new Promise((resolve) => setTimeout(resolve, 3000));

      const newAnalysis: AIAnalysisResult = {
        id: Date.now().toString(),
        timestamp: new Date(),
        analysisType: "user_behavior",
        summary: "用户活跃度分析显示，系统整体运行良好，用户参与度持续提升。",
        keyFindings: [
          "日活跃用户数增长12.5%，用户粘性显著提升",
          "移动端访问占比达到65%，移动化趋势明显",
          "用户平均在线时长增加18分钟，学习效果改善",
        ],
        recommendations: [
          "加强移动端功能优化，提升用户体验",
          "增加个性化推荐功能，提高用户参与度",
          "优化系统响应速度，减少用户等待时间",
        ],
        confidence: 92,
        status: "completed",
      };

      setAiAnalysisResults((prev) => [newAnalysis, ...prev]);
      message.success("AI分析生成完成！");
    } catch (error) {
      message.error("AI分析生成失败，请重试");
    } finally {
      setAiAnalyzing(false);
    }
  };

  // AI报告生成函数
  const generateAIReport = async (values: any) => {
    setGeneratingReport(true);
    try {
      // 模拟AI报告生成过程
      await new Promise((resolve) => setTimeout(resolve, 5000));

      const report: AIReport = {
        id: Date.now().toString(),
        title: `智教质学AI教学平台 - ${values.reportType || "综合"}分析报告`,
        generatedAt: new Date(),
        timeRange: `${dayjs(timeRange[0]).format("YYYY-MM-DD")} 至 ${dayjs(timeRange[1]).format("YYYY-MM-DD")}`,
        summary: "基于系统运行数据和用户行为分析，平台整体表现优秀，各项指标均呈现积极增长趋势。系统稳定性良好，用户体验持续改善。",
        overallScore: 87,
        sections: [
          {
            title: "用户行为分析",
            icon: <UserOutlined />,
            content: "用户活跃度持续提升，日活跃用户数增长12.5%，用户平均在线时长增加18分钟。移动端访问占比达到65%，用户粘性显著提升。",
            keyPoints: [
              "日活跃用户：567人（+12.5%）",
              "平均在线时长：45分钟（+18分钟）",
              "移动端访问占比：65%",
              "用户留存率：78.3%"
            ],
            status: "positive"
          },
          {
            title: "系统性能分析",
            icon: <DashboardOutlined />,
            content: "系统运行稳定，响应时间保持在200ms以内，服务器负载均衡良好。数据库查询优化效果显著，系统整体健康度达到96.5%。",
            keyPoints: [
              "系统响应时间：180ms",
              "服务器CPU使用率：45%",
              "数据库连接池：正常",
              "系统健康度：96.5%"
            ],
            status: "positive"
          },
          {
            title: "课程学习分析",
            icon: <BookOutlined />,
            content: "课程完成率稳步提升，热门课程参与度高。学生成绩分布合理，学习效果评估体系运行良好。",
            keyPoints: [
              "课程完成率：72.8%",
              "平均课程评分：4.6/5.0",
              "热门课程参与度：89%",
              "学习进度跟踪：完整"
            ],
            status: "positive"
          },
          {
            title: "安全风险评估",
            icon: <SecurityScanOutlined />,
            content: "系统安全状况良好，未发现重大安全漏洞。用户数据加密完善，访问控制机制有效。建议加强定期安全审计。",
            keyPoints: [
              "安全漏洞：0个高危",
              "数据加密：AES-256",
              "访问控制：完善",
              "安全审计：建议加强"
            ],
            status: "neutral"
          },
          {
            title: "数据趋势预测",
            icon: <BarChartOutlined />,
            content: "基于历史数据分析，预计下月用户增长率为8-12%，系统负载将保持在安全范围内。建议提前扩容服务器资源。",
            keyPoints: [
              "用户增长预测：8-12%",
              "系统负载预测：稳定",
              "资源需求：建议扩容",
              "风险等级：低"
            ],
            status: "warning"
          }
        ],
        status: "completed",
        recommendations: [
          "加强移动端功能优化，提升用户体验",
          "增加个性化推荐功能，提高用户参与度",
          "优化系统响应速度，减少用户等待时间",
          "加强定期安全审计和漏洞扫描",
          "提前规划服务器扩容，应对用户增长"
        ],
        nextSteps: [
          "实施移动端UI/UX优化方案",
          "部署个性化推荐算法",
          "进行系统性能调优",
          "制定安全审计计划",
          "评估服务器扩容需求"
        ]
      };

      setAiReport(report);
      message.success("AI报告生成完成！");
    } catch (error) {
      message.error("AI报告生成失败，请重试");
    } finally {
      setGeneratingReport(false);
    }
  };

  // 重新生成AI报告
  const regenerateAIReport = async () => {
    const values = await reportForm.validateFields();
    await generateAIReport(values);
  };

  // 下载PDF报告
  const downloadPDFReport = async () => {
    if (!aiReport) return;
    
    try {
      message.loading("正在生成PDF报告...", 0);
      
      // 触发PDF生成
      setShouldGeneratePDF(true);
      
      // 等待PDF生成完成
      setTimeout(() => {
        message.destroy();
        message.success("PDF报告生成完成！");
        setShouldGeneratePDF(false);
      }, 3000);
      
    } catch (error) {
      message.destroy();
      message.error("PDF报告生成失败，请重试");
      setShouldGeneratePDF(false);
    }
  };

  // 生成图表数据
  const generateChartData = () => {
    return {
      // 用户增长数据
      userGrowthData: {
        labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
        datasets: [
          {
            label: '学生用户',
            data: [320, 380, 420, 450, 480, 520, 567],
            backgroundColor: 'rgba(54, 162, 235, 0.6)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 2,
          },
          {
            label: '教师用户',
            data: [45, 52, 58, 62, 68, 72, 78],
            backgroundColor: 'rgba(255, 99, 132, 0.6)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 2,
          },
        ],
      },
      // 系统性能数据
      systemPerformanceData: {
        labels: ['CPU使用率', '内存使用率', '磁盘使用率', '网络带宽', '响应时间'],
        datasets: [
          {
            label: '当前值',
            data: [45, 62, 38, 75, 180],
            backgroundColor: [
              'rgba(54, 162, 235, 0.6)',
              'rgba(255, 99, 132, 0.6)',
              'rgba(255, 205, 86, 0.6)',
              'rgba(75, 192, 192, 0.6)',
              'rgba(153, 102, 255, 0.6)',
            ],
            borderColor: [
              'rgba(54, 162, 235, 1)',
              'rgba(255, 99, 132, 1)',
              'rgba(255, 205, 86, 1)',
              'rgba(75, 192, 192, 1)',
              'rgba(153, 102, 255, 1)',
            ],
            borderWidth: 2,
          },
        ],
      },
      // 课程分布数据
      courseDistributionData: {
        labels: ['计算机科学', '数学', '物理', '化学', '生物', '其他'],
        datasets: [
          {
            data: [30, 25, 15, 12, 10, 8],
            backgroundColor: [
              '#FF6384',
              '#36A2EB',
              '#FFCE56',
              '#4BC0C0',
              '#9966FF',
              '#FF9F40',
            ],
            borderWidth: 2,
            borderColor: '#fff',
          },
        ],
      },
      // 用户活跃度趋势
      userActivityData: {
        labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        datasets: [
          {
            label: '日活跃用户',
            data: [450, 520, 480, 600, 580, 420, 380],
            fill: true,
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 2,
            tension: 0.4,
          },
        ],
      },
    };
  };

  // 渲染AI分析结果
  const renderAIAnalysis = () => {
    return (
      <div>
        <div style={{ marginBottom: 16, textAlign: "center" }}>
          <Button
            type="primary"
            icon={aiAnalyzing ? <LoadingOutlined /> : <RobotOutlined />}
            loading={aiAnalyzing}
            onClick={generateNewAIAnalysis}
            size="large"
            style={{ marginRight: 16 }}
          >
            {aiAnalyzing ? "AI分析中..." : "获取AI分析"}
          </Button>
          <Button
            icon={<SyncOutlined />}
            onClick={generateNewAIAnalysis}
            disabled={aiAnalyzing}
          >
            重新生成
          </Button>
        </div>

        <Row gutter={[16, 16]}>
          {aiAnalysisResults.map((analysis) => (
            <Col xs={24} lg={12} key={analysis.id}>
              <Card
                title={
                  <Space>
                    <RobotOutlined style={{ color: "#1890ff" }} />
                    {analysis.analysisType === "user_behavior" && "用户行为分析"}
                    {analysis.analysisType === "system_performance" && "系统性能分析"}
                    {analysis.analysisType === "security_risk" && "安全风险分析"}
                    {analysis.analysisType === "data_trends" && "数据趋势分析"}
                    <Tag color="blue">{analysis.confidence}% 置信度</Tag>
                  </Space>
                }
                extra={
                  <Text type="secondary" style={{ fontSize: "12px" }}>
                    {dayjs(analysis.timestamp).format("MM-DD HH:mm")}
                  </Text>
                }
                style={{ marginBottom: 16 }}
              >
                <Paragraph strong style={{ marginBottom: 16 }}>
                  {analysis.summary}
                </Paragraph>
                
                <div style={{ marginBottom: 16 }}>
                  <Text strong>关键发现：</Text>
                  <ul style={{ marginTop: 8 }}>
                    {analysis.keyFindings.map((finding, index) => (
                      <li key={index}>{finding}</li>
                    ))}
                  </ul>
                </div>

                <div>
                  <Text strong>建议措施：</Text>
                  <ul style={{ marginTop: 8 }}>
                    {analysis.recommendations.map((rec, index) => (
                      <li key={index}>{rec}</li>
                    ))}
                  </ul>
                </div>
              </Card>
            </Col>
          ))}
        </Row>

        {aiAnalysisResults.length === 0 && (
          <Empty
            description="暂无AI分析结果"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        )}
      </div>
    );
  };

  if (loading && !systemOverview) {
    return (
      <div style={{ textAlign: "center", padding: "100px 0" }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>正在加载仪表板数据...</div>
      </div>
    );
  }

  return (
    <DashboardContainer>
      {/* 页面头部 */}
      <div style={{ marginBottom: 24 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Title level={3} style={{ margin: 0 }}>
              <DashboardOutlined /> 系统管理仪表板
            </Title>
            <Text type="secondary">
              欢迎回来，{user?.name}！今天是 {dayjs().format("YYYY年MM月DD日")}
            </Text>
          </Col>
          <Col>
            <Space>
              <RangePicker
                value={timeRange}
                onChange={(dates) =>
                  setTimeRange(dates as [dayjs.Dayjs, dayjs.Dayjs])
                }
                style={{ width: 240 }}
              />
              <QuickActionButton 
                icon={<DownloadOutlined />} 
                type="default"
                onClick={() => setAiReportModalVisible(true)}
              >
                AI报告生成
              </QuickActionButton>
              <QuickActionButton
                icon={<ReloadOutlined />}
                type="primary"
                onClick={loadData}
                loading={loading}
              >
                刷新数据
              </QuickActionButton>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 系统健康状态 */}
      {systemOverview && (
        <Alert
          message={
            <Space>
              <span>系统运行状态:</span>
              <Badge
                status={
                  systemOverview.serverStatus === "healthy"
                    ? "success"
                    : "warning"
                }
                text={
                  systemOverview.serverStatus === "healthy" ? "正常" : "异常"
                }
              />
              <span>健康度: {systemOverview.systemHealth}%</span>
            </Space>
          }
          type={
            systemOverview.serverStatus === "healthy" ? "success" : "warning"
          }
          showIcon
          style={{ marginBottom: 24 }}
        />
      )}

      {/* 核心指标 */}
      {renderSystemMetrics()}

      {/* 详细分析 */}
      <StyledCard>
        <Tabs activeKey={activeTab} onChange={setActiveTab} size="large">
          <TabPane
            tab={
              <Space>
                <TeamOutlined />
                用户分析
              </Space>
            }
            key="users"
          >
            <Row gutter={[24, 24]}>
              <Col span={16}>
                <Card title="用户增长趋势" size="small">
                  {renderUserGrowthChart()}
                </Card>
              </Col>
              <Col span={8}>
                <Card title="用户类型分布" size="small">
                  {renderUserDistributionChart()}
                </Card>
              </Col>
              <Col span={24}>
                <Card title="活跃用户排行榜" size="small">
                  {renderActiveUsersRanking()}
                </Card>
              </Col>
            </Row>
          </TabPane>

          <TabPane
            tab={
              <Space>
                <BookOutlined />
                课程分析
              </Space>
            }
            key="courses"
          >
            <Row gutter={[24, 24]}>
              <Col span={14}>
                <Card title="热门课程排行" size="small">
                  {renderPopularCoursesTable()}
                </Card>
              </Col>
              <Col span={10}>
                <Card title="学科表现分析" size="small">
                  {renderPerformanceRadarChart()}
                </Card>
              </Col>
              <Col span={24}>
                <Card title="课程类别分布" size="small">
                  <Row gutter={16}>
                    {courseAnalytics?.categoryDistribution.map(
                      (category, index) => (
                        <Col span={4.8} key={category.category}>
                          <div style={{ textAlign: "center", padding: "16px" }}>
                            <div
                              style={{
                                fontSize: "24px",
                                fontWeight: "bold",
                                color: COLORS[index % COLORS.length],
                                marginBottom: "8px",
                              }}
                            >
                              {category.count}
                            </div>
                            <div
                              style={{
                                fontSize: "14px",
                                color: "#666",
                                marginBottom: "4px",
                              }}
                            >
                              {category.category}
                            </div>
                            <div style={{ fontSize: "12px", color: "#999" }}>
                              {category.percentage}%
                            </div>
                          </div>
                        </Col>
                      )
                    )}
                  </Row>
                </Card>
              </Col>
            </Row>
          </TabPane>

          <TabPane
            tab={
              <Space>
                <BellOutlined />
                <Badge
                  count={systemAlerts.filter((a) => !a.resolved).length}
                  size="small"
                >
                  系统监控
                </Badge>
              </Space>
            }
            key="monitoring"
          >
            <Row gutter={[24, 24]}>
              <Col span={12}>
                <Card title="系统警告" size="small">
                  {renderSystemAlerts()}
                </Card>
              </Col>
              <Col span={12}>
                <Card title="系统性能指标" size="small">
                  <Space
                    direction="vertical"
                    style={{ width: "100%" }}
                    size="large"
                  >
                    <div>
                      <div style={{ marginBottom: 8 }}>
                        <Text>CPU 使用率</Text>
                        <Text style={{ float: "right" }}>68%</Text>
                      </div>
                      <Progress percent={68} strokeColor="#1890ff" />
                    </div>
                    <div>
                      <div style={{ marginBottom: 8 }}>
                        <Text>内存使用率</Text>
                        <Text style={{ float: "right" }}>45%</Text>
                      </div>
                      <Progress percent={45} strokeColor="#52c41a" />
                    </div>
                    <div>
                      <div style={{ marginBottom: 8 }}>
                        <Text>磁盘使用率</Text>
                        <Text style={{ float: "right" }}>72%</Text>
                      </div>
                      <Progress percent={72} strokeColor="#faad14" />
                    </div>
                    <div>
                      <div style={{ marginBottom: 8 }}>
                        <Text>网络带宽</Text>
                        <Text style={{ float: "right" }}>38%</Text>
                      </div>
                      <Progress percent={38} strokeColor="#722ed1" />
                    </div>
                  </Space>
                </Card>
              </Col>
            </Row>
          </TabPane>

          <TabPane
            tab={
              <Space>
                <RobotOutlined />
                AI数据分析
              </Space>
            }
            key="ai-analysis"
          >
            {renderAIAnalysis()}
          </TabPane>

          <TabPane
            tab={
              <Space>
                <GlobalOutlined />
                数据概览
              </Space>
            }
            key="overview"
          >
            <Row gutter={[24, 24]}>
              <Col span={24}>
                <Alert
                  message="数据统计说明"
                  description="以下数据基于最近30天的平台活动统计，每小时更新一次。如需详细报告，请点击导出功能。"
                  type="info"
                  showIcon
                  style={{ marginBottom: 16 }}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="今日新增用户"
                  value={67}
                  prefix={<UserOutlined />}
                  suffix="人"
                  valueStyle={{ color: "#1890ff" }}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="今日活跃用户"
                  value={534}
                  prefix={<TeamOutlined />}
                  suffix="人"
                  valueStyle={{ color: "#52c41a" }}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="今日学习时长"
                  value={1245}
                  prefix={<ClockCircleOutlined />}
                  suffix="小时"
                  valueStyle={{ color: "#faad14" }}
                />
              </Col>
              <Col span={12}>
                <Card title="最近7天趋势" size="small">
                  <ResponsiveContainer width="100%" height={200}>
                    <LineChart data={userStatistics?.activeUserTrend || []}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="date" />
                      <YAxis />
                      <RechartsTooltip />
                      <RechartsLine
                        type="monotone"
                        dataKey="activeUsers"
                        stroke="#1890ff"
                        strokeWidth={2}
                        name="活跃用户"
                      />
                    </LineChart>
                  </ResponsiveContainer>
                </Card>
              </Col>
              <Col span={12}>
                <Card title="登录率趋势" size="small">
                  <ResponsiveContainer width="100%" height={200}>
                    <AreaChart data={userStatistics?.activeUserTrend || []}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="date" />
                      <YAxis />
                      <RechartsTooltip />
                      <RechartsArea
                        type="monotone"
                        dataKey="loginRate"
                        stroke="#52c41a"
                        fill="#52c41a"
                        fillOpacity={0.3}
                        name="登录率(%)"
                      />
                    </AreaChart>
                  </ResponsiveContainer>
                </Card>
              </Col>
            </Row>
          </TabPane>
        </Tabs>
      </StyledCard>

      {/* AI报告生成模态框 */}
      <Modal
        title={
          <Space>
            <RobotOutlined style={{ color: "#1890ff" }} />
            AI智能报告生成
          </Space>
        }
        open={aiReportModalVisible}
        onCancel={() => {
          setAiReportModalVisible(false);
          setAiReport(null);
          reportForm.resetFields();
        }}
        footer={null}
        width={1000}
        destroyOnClose
      >
        {!aiReport ? (
          <div>
            <Alert
              message="AI报告生成说明"
              description="AI将基于当前系统数据，从多个角度深度分析平台运行状况，生成专业的分析报告。报告包含用户行为、系统性能、安全风险、数据趋势等多个维度的分析。"
              type="info"
              showIcon
              style={{ marginBottom: 24 }}
            />
            
            <Form form={reportForm} layout="vertical">
              <Form.Item
                name="reportType"
                label="报告类型"
                initialValue="综合"
                rules={[{ required: true, message: "请选择报告类型" }]}
              >
                <Select placeholder="选择报告类型">
                  <Select.Option value="综合">综合分析报告</Select.Option>
                  <Select.Option value="用户">用户行为分析</Select.Option>
                  <Select.Option value="系统">系统性能分析</Select.Option>
                  <Select.Option value="安全">安全风险评估</Select.Option>
                  <Select.Option value="趋势">数据趋势预测</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="description"
                label="特殊要求"
                initialValue=""
              >
                <Input.TextArea
                  placeholder="请输入特殊分析要求（可选）"
                  rows={3}
                  maxLength={200}
                  showCount
                />
              </Form.Item>

              <div style={{ textAlign: "center", marginTop: 24 }}>
                <Button
                  type="primary"
                  size="large"
                  icon={<RobotOutlined />}
                  loading={generatingReport}
                  onClick={() => {
                    reportForm.validateFields().then(generateAIReport);
                  }}
                  style={{ marginRight: 16 }}
                >
                  {generatingReport ? "AI正在生成报告..." : "开始生成AI报告"}
                </Button>
                <Button
                  onClick={() => {
                    setAiReportModalVisible(false);
                    setAiReport(null);
                    reportForm.resetFields();
                  }}
                >
                  取消
                </Button>
              </div>
            </Form>
          </div>
        ) : (
          <div>
            {/* 报告头部信息 */}
            <div style={{ 
              background: "#f8f9fa", 
              padding: "20px", 
              borderRadius: "8px",
              marginBottom: "24px"
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
                <Title level={4} style={{ margin: 0 }}>{aiReport.title}</Title>
                <Space>
                  <Tag color="blue">评分: {aiReport.overallScore}/100</Tag>
                  <Tag color="green">已完成</Tag>
                </Space>
              </div>
              <Descriptions size="small" column={2}>
                <Descriptions.Item label="生成时间">
                  {aiReport.generatedAt.toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="分析周期">
                  {aiReport.timeRange}
                </Descriptions.Item>
              </Descriptions>
            </div>

            {/* 执行摘要 */}
            <Card title="执行摘要" size="small" style={{ marginBottom: "16px" }}>
              <Paragraph>{aiReport.summary}</Paragraph>
            </Card>

            {/* 详细分析 */}
            <Collapse defaultActiveKey={["0"]} style={{ marginBottom: "16px" }}>
              {aiReport.sections.map((section, index) => (
                <Collapse.Panel
                  key={index}
                  header={
                    <Space>
                      {section.icon}
                      <span>{section.title}</span>
                      <Tag 
                        color={
                          section.status === "positive" ? "green" :
                          section.status === "negative" ? "red" :
                          section.status === "warning" ? "orange" : "default"
                        }
                      >
                        {section.status === "positive" ? "优秀" :
                         section.status === "negative" ? "需改进" :
                         section.status === "warning" ? "注意" : "正常"}
                      </Tag>
                    </Space>
                  }
                >
                  <div style={{ marginBottom: "16px" }}>
                    <Paragraph>{section.content}</Paragraph>
                  </div>
                  
                  {/* 添加图表显示 */}
                  {index === 0 && (
                    <div style={{ marginBottom: "20px" }}>
                      <Row gutter={[16, 16]}>
                        <Col span={12}>
                          <Card title="用户增长趋势" size="small">
                            <Bar 
                              data={generateChartData().userGrowthData}
                              options={{
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                  legend: {
                                    position: 'top' as const,
                                  },
                                },
                              }}
                              height={200}
                            />
                          </Card>
                        </Col>
                        <Col span={12}>
                          <Card title="用户活跃度趋势" size="small">
                            <Line 
                              data={generateChartData().userActivityData}
                              options={{
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                  legend: {
                                    position: 'top' as const,
                                  },
                                },
                              }}
                              height={200}
                            />
                          </Card>
                        </Col>
                      </Row>
                    </div>
                  )}
                  
                  {index === 1 && (
                    <div style={{ marginBottom: "20px" }}>
                      <Row gutter={[16, 16]}>
                        <Col span={12}>
                          <Card title="系统性能指标" size="small">
                            <Bar 
                              data={generateChartData().systemPerformanceData}
                              options={{
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                  legend: {
                                    position: 'top' as const,
                                  },
                                },
                              }}
                              height={200}
                            />
                          </Card>
                        </Col>
                        <Col span={12}>
                          <Card title="系统健康度" size="small">
                            <Doughnut
                              data={{
                                labels: ['健康', '警告', '异常'],
                                datasets: [{
                                  data: [96.5, 2.5, 1],
                                  backgroundColor: ['#52c41a', '#faad14', '#ff4d4f'],
                                }]
                              }}
                              options={{
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                  legend: {
                                    position: 'top' as const,
                                  },
                                },
                              }}
                              height={200}
                            />
                          </Card>
                        </Col>
                      </Row>
                    </div>
                  )}
                  
                  {index === 2 && (
                    <div style={{ marginBottom: "20px" }}>
                      <Row gutter={[16, 16]}>
                        <Col span={12}>
                          <Card title="课程类别分布" size="small">
                            <Pie 
                              data={generateChartData().courseDistributionData}
                              options={{
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                  legend: {
                                    position: 'top' as const,
                                  },
                                },
                              }}
                              height={200}
                            />
                          </Card>
                        </Col>
                        <Col span={12}>
                          <Card title="学习效果评估" size="small">
                            <div style={{ textAlign: 'center', padding: '20px' }}>
                              <Progress
                                type="circle"
                                percent={72.8}
                                format={(percent) => `${percent}%`}
                                strokeColor="#52c41a"
                                size={120}
                              />
                              <div style={{ marginTop: 16 }}>
                                <Text strong>课程完成率</Text>
                              </div>
                            </div>
                          </Card>
                        </Col>
                      </Row>
                    </div>
                  )}
                  
                  <div>
                    <Text strong>关键指标：</Text>
                    <ul style={{ marginTop: "8px" }}>
                      {section.keyPoints.map((point, idx) => (
                        <li key={idx}>{point}</li>
                      ))}
                    </ul>
                  </div>
                </Collapse.Panel>
              ))}
            </Collapse>

            {/* 建议措施 */}
            <Card title="建议措施" size="small" style={{ marginBottom: "16px" }}>
              <Timeline>
                {aiReport.recommendations.map((rec, index) => (
                  <Timeline.Item 
                    key={index}
                    dot={<BulbOutlined style={{ color: "#1890ff" }} />}
                  >
                    {rec}
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>

            {/* 后续行动 */}
            <Card title="后续行动" size="small" style={{ marginBottom: "24px" }}>
              <Timeline>
                {aiReport.nextSteps.map((step, index) => (
                  <Timeline.Item 
                    key={index}
                    dot={<CheckCircleOutlined style={{ color: "#52c41a" }} />}
                  >
                    {step}
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>

            {/* 操作按钮 */}
            <div style={{ textAlign: "center" }}>
              <Space size="large">
                <Button
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={downloadPDFReport}
                  size="large"
                >
                  下载PDF报告
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={regenerateAIReport}
                  loading={generatingReport}
                  size="large"
                >
                  重新生成
                </Button>
                <Button
                  onClick={() => {
                    setAiReportModalVisible(false);
                    setAiReport(null);
                    reportForm.resetFields();
                  }}
                  size="large"
                >
                  关闭
                </Button>
              </Space>
            </div>
          </div>
        )}
      </Modal>

      {/* PDF报告生成组件 */}
      {aiReport && shouldGeneratePDF && (
        <PDFReportGenerator
          aiReport={aiReport}
          onComplete={() => {
            message.success("PDF报告已生成并下载完成！");
            setShouldGeneratePDF(false);
          }}
        />
      )}
    </DashboardContainer>
  );
};

export default AdminDashboard;
